package com.aaa.daydemo111.demo4;

import sun.misc.Lock;

import java.util.Arrays;

/**
 * @Description:
 * @author:LiWei
 * @date:2022年11月01日9:58
 */
public class TestSafe {
    private static String[]arr=new String[2];
    private static int index=0;
    private static Object lock=new Object();
    public static void main(String[] args) throws InterruptedException {

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    if (arr[index] == null) {
                        arr[index] = "aaa";
                        index++;
                    }
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    if (arr[index] == null) {
                        arr[index] = "bbb";
                        index++;
                    }
                }
            }
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
        System.out.println(Arrays.toString(arr));
    }
}
